package com.hlingsoft.cms.action;

import com.hlingsoft.cms.alipay.util.AlipayNotify;
import com.hlingsoft.cms.constant.OrderInfoConstant;
import com.hlingsoft.cms.entity.AppUser;
import com.hlingsoft.cms.entity.OrderInfo;
import com.hlingsoft.cms.exception.FolderNotFoundException;
import com.hlingsoft.cms.service.AdminPushService;
import com.hlingsoft.cms.util.Common;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by selbylei on 2015/5/28.
 */

@Controller
@RequestMapping("/alipay")
public class AlipayAction extends BaseAction{


    /**
     * 支付宝异步通知
     * @param request
     * @return
     * @throws FolderNotFoundException
     */
    @RequestMapping(value = "/notify.json")
    @ResponseBody
    public String notify(HttpServletRequest request)
            throws FolderNotFoundException {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);

        }
//        String trade_no = request.getParameter("trade_no");             //支付宝交易号
        String order_no = request.getParameter("out_trade_no");         //获取订单号
//        String total_fee = request.getParameter("total_fee");           //获取总金额
//        String subject = new String(Common.encodeStr(request.getParameter("total_fee")));//商品名称、订单名称
        String body = "";


        if (AlipayNotify.verify(params)) {
            if (request.getParameter("body") != null) {
                body = new String(Common.encodeStr(body));//商品描述、订单备注、描述
            }
            String buyer_email = request.getParameter("buyer_email");       //买家支付宝账号
            String trade_status = request.getParameter("trade_status");     //交易状态

            if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
                OrderInfo orderInfo = orderInfoDao.getOrderByOrderId(order_no);
                orderInfo.setStatus(OrderInfoConstant.WAITDELIVER);     //支付成功后订单状态，等待发货
                orderInfoDao.updateOrderInfo(orderInfo);

                final AppUser user = appUserDao.getUserById(orderInfo.getAppUserId());
                String alert = user.getName()+"您已支付成功,小飞已忙着发货";
                adminPushService.pushToClient(alert, new ArrayList<String>() {
                    {
                        add(user.getUdId());
                    }
                }, AdminPushService.JOB, false,true);
            }
            return "success";
        } else {
            return "fail";
        }
    }

}
